﻿#include <QFile>
#include <assert.h>
#include <qDebug>
#include <QDir>
#include "corecrt_math_defines.h"
#include "ProjectTreeData.h"
#include "BaseModule/QJsonHelper/QJsonSerializer.h"
#include "BaseModule/GlobalHelper.h"
#include "BaseModule/IBaseSignal.h"
#include "ProjectTreeDataManager.h"


namespace DataManager
{
    // <ProjectTreeData>
    ProjectTreeData::~ProjectTreeData()
    {
    }
    
    ProjectTreeData* ProjectTreeData::m_instance = nullptr;

    ProjectTreeData* ProjectTreeData::getInstance()
    {
        if (m_instance == nullptr)
        {
            m_instance = new ProjectTreeData;
        }
        return m_instance;
    }

    void ProjectTreeData::setTreeView(QTreeView* treeView)
    {
        m_treeView = treeView;
    }

    int ProjectTreeData::generateProjectTreeItemID()
    {
        m_projectTreeItemMaxID++;
        return m_projectTreeItemMaxID;
    }

    void ProjectTreeData::resetProjectTreeItemMaxID()
    {
        m_projectTreeItemMaxID = 0;
    }

    void ProjectTreeData::setProjectTreeAllItemID()
    {
        if (!m_isSavaProject)
            resetProjectTreeItemMaxID();
        auto model = (QStandardItemModel*)m_treeView->model();
        for (int i = 0; i < model->rowCount(); ++i)
        {
            auto item = model->item(i);
            traverseItemSetID(item);
        }
    }

    void ProjectTreeData::traverseItemSetID(QStandardItem* item)
    {
        if (!item)
            return;
        if (!m_isSavaProject)
            item->setData(generateProjectTreeItemID(), Qt::UserRole + 10);
        else
        {
            if (!item->data(Qt::UserRole + 10).isNull())
            {
                auto _itemID = item->data(Qt::UserRole + 10).toInt();
                if (item->parent() == nullptr) // 是根节点
                {
                    m_itemParentIDList.append(_itemID);
                }
                else
                {
                    if (!item->parent()->data(Qt::UserRole + 10).isNull())
                    {
                        m_itemParentIDList.append(item->parent()->data(Qt::UserRole + 10).toInt());
                    }
                }
                m_itemOwnIDList.append(_itemID);
                m_itemNameList.append(item->text());
            }
        }

        for (int row = 0; row < item->rowCount(); ++row)
        {
            auto childItem = item->child(row, 0);
            if (childItem)
                traverseItemSetID(childItem);
        }
    }

    QStandardItem* ProjectTreeData::getProjectTreeItemByID(int ID)
    {
        auto model = (QStandardItemModel*)m_treeView->model();
        for (int i = 0; i < model->rowCount(); ++i)
        {
            auto item = model->item(i);
            auto _item = traverseGetItemByID(item, ID);
            if (_item)
                return _item;
        }
        return nullptr;
    }

    QStandardItem* ProjectTreeData::traverseGetItemByID(QStandardItem* item, int ID)
    {
        if (!item)
            return nullptr;

        if (!item->data(Qt::UserRole + 10).isNull())
        {
            if (item->data(Qt::UserRole + 10).toInt() == ID)
                return item;
        }
        for (int row = 0; row < item->rowCount(); ++row)
        {
            auto _item = traverseGetItemByID(item->child(row), ID);
            if (_item)
                return _item;
        }
        return nullptr;
    }

    int ProjectTreeData::getCurrentQStandardItemID()
    {
        auto _item = getCurrentQStandardItem();
        if (_item)
        {
            return _item->data(Qt::UserRole + 10).toInt();
        }
        return -1;
    }

    QStandardItem* ProjectTreeData::getCurrentQStandardItem()
    {
        auto _currentIndex = m_treeView->currentIndex();
        if (_currentIndex.isValid())
        {
            auto _item = (QStandardItem *)_currentIndex.internalPointer();
            if (_item)
            {
                return _item;
            }
        }
        return nullptr;
    }

    void ProjectTreeData::appendPasteAndImportItemData(int srcID, int dstID, QString importItemFilePath)
    {
        m_pasteAndImportItemData.append(qMakePair(srcID, dstID));
        if (srcID == -1)
        {
            m_importItemDataList.append(qMakePair(dstID, importItemFilePath));

            auto _importDatasPath = GlobalHelperInstance->getImportDataTempDir();
            QFile::copy(importItemFilePath, _importDatasPath + "/" + importItemFilePath.split('/').last());
        }
    }

    void ProjectTreeData::removePasteAndImportItemData(int dstID)
    {
        for (auto importData : m_pasteAndImportItemData)
        {
            if (importData.second == dstID)
            {
                m_pasteAndImportItemData.removeOne(importData);
            }
        }
        for (auto importData : m_importItemDataList)
        {
            if (importData.first == dstID)
            {
                auto _filePath = importData.second;
                QFileInfo fileInfo(_filePath);
                if (fileInfo.suffix() == "txt" || fileInfo.suffix() == "csv") // 是txt或csv文件
                {
                    emit IBaseSignalInstance->signal_removeImprotTextData(dstID);
                }
                m_importItemDataList.removeOne(importData);
                QFile::remove(importData.second);
            }
        }
    }

    QList<QPair<int, QString>> ProjectTreeData::getImportItemDataList()
    {
        return m_importItemDataList;
    }

    void ProjectTreeData::sort()
    {
    }

    void ProjectTreeData::clear()
    {
        m_projectTreeItemMaxID = 0;
        m_pasteAndImportItemData.clear();
        m_importItemDataList.clear();
        m_itemParentIDList.clear();
        m_itemOwnIDList.clear();
        m_itemNameList.clear();
    }

    void ProjectTreeData::readConfig()
    {
        QString configFilePath = GlobalHelperInstance->getProjectTempFilePath() + "/ProjectTreeData.json";
        QByteArray _strJson;
        if (GlobalHelperInstance->readFile(configFilePath, _strJson))
        {
            QJsonHelper::QJsonSerializer _jsonSerializer;
            auto _ProjectTreeData = _jsonSerializer.deserialize<DataManager::ProjectTreeDataManager*>(_strJson);
            if (_ProjectTreeData)
            {
                m_configData = QSharedPointer<DataManager::ProjectTreeDataManager>(_ProjectTreeData);
                auto _simulatationDataFilePaths = m_configData->getSimulationDataFilePaths();
                QList<QString> _filePathsList = _simulatationDataFilePaths.split(',');
                if (!(_filePathsList.count() == 1 && _filePathsList.first().isEmpty()))
                {
                    for (auto& _filePath : _filePathsList)
                    {
                        _filePath = GlobalHelperInstance->getSimulationDataTempDir() + "/" + _filePath.split('/').last(); // 替换为当前安装目录路径
                    }
                    if (!_filePathsList.isEmpty())
                    {
                        emit auto success = IBaseSignalInstance->signal_importProjectData(_filePathsList);
                        if (!success)
                            return;
                    }
                }

                //执行后续操作前必须先打开仿真数据，打开仿真数据会清空所有项目树，所以不考虑先导入数据再打开仿真数据的顺序问题
                m_itemParentIDList = m_configData->getItemParentIDList();
                m_itemOwnIDList = m_configData->getItemOwnIDList();
                m_itemNameList = m_configData->getItemNameList();
                auto _pasteItemIDList = m_configData->getPasteAndImportItemData();
                auto _pasteAndImportItemDataList = GlobalHelperInstance->convertStringToIntIntQList(_pasteItemIDList);
                auto _importItemDataStr = m_configData->getImportItemDataList();
                auto _importItemDataList = GlobalHelperInstance->convertStringToIntQStringQList(_importItemDataStr);
                for (auto& _importItemData : _importItemDataList)
                {
                    _importItemData = qMakePair(_importItemData.first, GlobalHelperInstance->getImportDataTempDir() + "/" + _importItemData.second.split('/').last()); // 替换为当前安装目录路径
                }
                emit IBaseSignalInstance->signal_textImportDataReadConfig();
                // 遍历_pasteAndImportItemDataTotal，复制粘贴和导入数据
                //遍历项目树对照m_itemOwnIDList删除无用节点
                for (auto _pasteAndImportItemData : _pasteAndImportItemDataList)
                {
                    if (_pasteAndImportItemData.first == -1)//源节点Id为-1，表示是导入节点
                    {
                        for (auto _importItemData : _importItemDataList)
                        {
                            if (_pasteAndImportItemData.second == _importItemData.first)
                            {
                                QFileInfo fileInfo(_importItemData.second);
                                if (!fileInfo.exists())
                                    continue;
                                emit IBaseSignalInstance->singal_toolButtonDataImport(_importItemData.second);
                            }
                        }                      
                    }
                    else
                    {
                        auto _srcItem = getProjectTreeItemByID(_pasteAndImportItemData.first);
                        if (!_srcItem->hasChildren())
                            emit IBaseSignalInstance->signal_pasteFileItemData(_pasteAndImportItemData.first, _pasteAndImportItemData.second);
                        else
                            emit IBaseSignalInstance->signal_pasteDirectoryItemData(_pasteAndImportItemData.first, _pasteAndImportItemData.second);
                    }
                }
                auto model = (QStandardItemModel*)m_treeView->model();
                for (int i = 0; i < model->rowCount(); ++i)
                {
                    auto item = model->item(i);
                    if (!item->data(Qt::UserRole + 10).isNull())
                    {
                        auto _itemID = item->data(Qt::UserRole + 10).toInt();
                        if (!m_itemOwnIDList.contains(_itemID))
                        {
                            model->removeRow(item->row());
                            continue;
                        }
                    }
                    
                }
            }
        }
    }

    void ProjectTreeData::writeConfig()
    {
        auto _ProjectTempFilePath = GlobalHelperInstance->getProjectTempFilePath();
        QString configFilePath = _ProjectTempFilePath + "/ProjectTreeData.json";
        if (!m_configData)
        {
            m_configData = QSharedPointer<DataManager::ProjectTreeDataManager>(new DataManager::ProjectTreeDataManager());
        }
        else
        {
            m_configData->clear();
        }
        m_configData->setSimulationDataFilePaths(GlobalHelperInstance->getSimulationDataFilePath());

        m_isSavaProject = true;

        m_itemParentIDList.clear();
        m_itemOwnIDList.clear();
        m_itemNameList.clear();

        setProjectTreeAllItemID();
        m_configData->setItemParentIDList(m_itemParentIDList);
        m_configData->setItemOwnIDList(m_itemOwnIDList);
        m_configData->setItemNameList(m_itemNameList);

        emit IBaseSignalInstance->signal_textImportDataWriteConfig();
        auto pasteAndImportItemData = GlobalHelperInstance->convertIntIntQListToQString(m_pasteAndImportItemData);
        m_configData->setPasteAndImportItemData(pasteAndImportItemData);

        auto _importItemDataStr = GlobalHelperInstance->convertIntQStringQListToQString(m_importItemDataList);
        m_configData->setImportItemDataList(_importItemDataStr);

        QJsonHelper::QJsonSerializer _jsonSerializer;
        QByteArray bytes = _jsonSerializer.serialize<DataManager::ProjectTreeDataManager*>(m_configData.get());
        GlobalHelperInstance->writeFile(configFilePath, bytes);
        m_isSavaProject = false;
    }

    void ProjectTreeData::resetData()
    {
        // clear();
        // setCurrentProjectTreeItemID(0);
        // DataManager::ProjectTreeItemData::resetMaxID();
        // if (!m_configData)
        //{
        //     m_configData = QSharedPointer<DataManager::ProjectTreeDataManager>(new DataManager::ProjectTreeDataManager());
        // }
        // else
        //{
        //     m_configData->clear();
        // }
    }

    void ProjectTreeData::dataToByteArray(QByteArray* byteArray)
    {
        // if (!m_ProjectTreeItemDataList.isEmpty())
        //{
        //     QByteArray _strJson;
        //     QString configFilePath = BaseModule::GlobalHelper::getProjectTempIODir() + "/ProjectTreeData.json";
        //     QFile file(configFilePath);
        //     if (!file.exists())
        //     {
        //         writeConfig();
        //     }
        //     if (BaseModule::GlobalHelper::readFile(configFilePath, _strJson))
        //     {
        //         byteArray->append(_strJson);
        //     }
        // }
    }

} // namespace DataManager
